import { difference } from "@turf/difference";
import * as turf from "@turf/helpers";

const GAODE_KEY = import.meta.env.VITE_GAODE_KEY;
interface LatLng {
  lat: number;
  lng: number;
}
export function isSamePoint(latlngA: LatLng, latlngB: LatLng) {
  return latlngA.lat === latlngB.lat && latlngA.lng === latlngB.lng;
}

export const getAssetsFile = (url: string) => {
  return new URL(`../assets/${url}`, import.meta.url).href;
};

export const diffence = (polygon: Array<Array<Array<number>>>) => {
  const bigPolygon = turf.polygon([
    [
      [65.52044581250786, 44.23236335614499],
      [65.52044581250786, 3.0553241760614327],
      [142.1835851562019, 3.0553241760614327],
      [142.1835851562019, 44.23236335614499],
      [65.52044581250786, 44.23236335614499],
    ],
  ]);
  const smallPolygon = turf.polygon(polygon);

  const rst = difference(turf.featureCollection([bigPolygon, smallPolygon]));
  return rst;
};

export const getLocationInfo = async () => {
  const url = "https://restapi.amap.com/v3/ip?key=" + GAODE_KEY;
  let rst = await fetch(url);
  rst = rst.json();
  return rst;
};

export const getPOIByKeyword = async (keyword: string) => {
  const url = `https://restapi.amap.com/v3/place/text?keywords=${keyword}&city=上海&offset=10&page=1&key=${GAODE_KEY}&extensions=all`;
  let rst = await fetch(url);
  rst = rst.json();
  return rst;
};

export const getAddressByLonLat = async (lon: Number, lat: Number) => {
  const url = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${lon},${lat}&key=${GAODE_KEY}&radius=1000&extensions=all`;
  let rst = await fetch(url);
  rst = rst.json();
  return rst;
};
